package com.un.ebs.memorial.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.un.ebs.core.util.OSSUtil;
import com.un.ebs.memorial.domain.MemorialResource;
import com.un.ebs.memorial.enums.MemorialResourceTypeEnum;
import com.un.ebs.memorial.mapper.MemorialResourceMapper;
import com.un.ebs.memorial.service.MemorialResourceService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liubo
 * @since 2020-03-12
 */
@Service
public class MemorialResourceServiceImpl extends ServiceImpl<MemorialResourceMapper, MemorialResource> implements MemorialResourceService {

    private final String prefix = "memorial";

    @Override
    public void add(MemorialResourceTypeEnum type, List<MultipartFile> files) {
        for (MultipartFile file : files) {
            MemorialResource obj = new MemorialResource();
            obj.setSort(getBaseMapper().maxSort());
            obj.setName(file.getOriginalFilename());
            String url = OSSUtil.upload(file, String.format("%s/%s/", prefix, type.toString()));
            obj.setUrl(url);
            obj.setType(type.getCode());
            obj.insert();
        }
    }

    @Override
    public void delete(String id) {
        MemorialResource obj = baseMapper.selectById(id);
        if (obj == null) {
            return;
        }
        OSSUtil.delete(obj.getUrl());
        baseMapper.deleteById(id);
    }

    @Override
    public MemorialResource queryById(String id) {
        return getBaseMapper().selectById(id);
    }

    @Override
    public List<MemorialResource> queryAll() {
        LambdaQueryWrapper<MemorialResource> lq = Wrappers.lambdaQuery();
        lq.eq(MemorialResource::getIsDelete, false);
        lq.orderByAsc(MemorialResource::getSort);
        List<MemorialResource> list = baseMapper.selectList(lq);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setUrl(OSSUtil.getObjectUrl(list.get(i).getUrl()).toString());
        }
        return list;
    }

    @Override
    public void changeSort(String id, int index) {
        MemorialResource obj = getById(id);
        obj.setSort(index);
        getBaseMapper().updateById(obj);
    }

}